/*自适应动态阈值范围，获得一个相对最佳的阈值*/
void IMAGE_MIDDLE_SET()
{
	// 大津法
	unsigned long Amount = 0;
	unsigned long PixelBack = 0;
	unsigned long PixelshortegralBack = 0;
	unsigned long Pixelshortegral = 0;
	signed long PixelshortegralFore = 0;
	signed long PixelFore = 0;
	float OmegaBack, OmegaFore, MicroBack, MicroFore, SigmaB, Sigma; // 类间方差
	signed short MinValue = 0, MaxValue = 255;
	unsigned char HistoGram[256] = { 0 };
	for (int i = 0; i < MAX_VIDEO_LINE; i++)
		for (int j = 0; j < MAX_VIDEO_POINT; j++)
			HistoGram[g_VideoImageData[i][j]]++;
	for (; MinValue < 256 && HistoGram[MinValue] == 0; MinValue++);
	for (; MaxValue > MinValue && HistoGram[MaxValue] == 0 && MaxValue != MinValue; MaxValue--);
	if (MaxValue == MinValue)
	{
		IMAGE_MIDDLE = MaxValue;
	}
	else
	{
		if ((MinValue + 1) == MaxValue)
		{
			IMAGE_MIDDLE = MinValue;
		}
		else
		{
			Pixelshortegral = 0;
			SigmaB = -1;
			for (int i = MinValue; i <= MaxValue; i++)
			{
				Amount += HistoGram[i];  // 像素点总数
				Pixelshortegral += HistoGram[i] * i;  // 灰度值总数
			}
			float average_pixel = float(Pixelshortegral) / Amount;
			for (int i = MinValue; i <= MaxValue; i++)
			{
				PixelBack = PixelBack + HistoGram[i];  // 前景像素点数
				PixelFore = Amount - PixelBack;  // 背景像素点数
				OmegaBack = ((float)PixelBack) / Amount;  // 前景像素百分比
				OmegaFore = ((float)PixelFore) / Amount;  // 背景像素百分比
				PixelshortegralBack += HistoGram[i] * i; // 前景灰度值
				PixelshortegralFore = Pixelshortegral - PixelshortegralBack;  // 背景灰度值
				MicroBack = ((float)PixelshortegralBack) / PixelBack;  // 前景灰度百分比
				MicroFore = ((float)PixelshortegralFore) / PixelFore;  // 背景灰度百分比
				Sigma = PixelBack * (MicroBack - average_pixel) * (MicroBack - average_pixel) + PixelFore * (MicroFore - average_pixel) * (MicroFore - average_pixel);  // 类间方差
				if (Sigma > SigmaB)
				{
					SigmaB = Sigma;
					IMAGE_MIDDLE = i;
				}
			}
		}
	}
}